import 'package:flutter_admin/models/user_info.dart';
import 'package:flutter_admin/pages/common/cry/cry_button_bar.dart';
import 'package:flutter_admin/pages/common/cry/cry_buttons.dart';
import 'package:flutter_admin/pages/common/cry/cry_dialog.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_input.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_select.dart';
import 'package:flutter_admin/pages/common/cry/model/order_item_model.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/cry_button.dart';
import 'package:flutter_admin/pages/common/cry/cry_data_table.dart';
import 'package:flutter_admin/api/odoo/purchase_supplier_evaluation_odoo_api.dart';
import 'package:flutter_admin/constants/enum.dart';
import 'package:flutter_admin/generated/l10n.dart';
import 'package:flutter_admin/pages/common/cry/model/page_model.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/models/odoo/purchase_supplier_evaluation.dart';
import 'package:flutter_admin/pages/odoo/purchase_supplier_evaluation/purchase_supplier_evaluation_edit.dart';
import 'package:flutter_admin/pages/odoo/purchase_supplier_evaluation/purchase_supplier_evaluation_dialog.dart';
import 'package:flutter_admin/pages/common/cry/utils/cry_utils.dart';
import 'package:flutter_admin/pages/common/cry/vo/select_option_vo.dart';
import 'package:flutter_admin/api/odoo/dynamic_data_api.dart';
import 'package:flutter_admin/pages/common/years_date.dart';
import 'package:flutter_admin/utils/adaptive_util.dart';
import 'package:flutter_admin/utils/eventbus.dart';
import 'package:flutter_admin/utils/store_util.dart';
import 'package:flutter_admin/utils/utils.dart';
import 'evaluate.dart';
import 'evaluate_view.dart';

class PurchaseSupplierEvaluationList extends StatefulWidget {
  PurchaseSupplierEvaluationList({Key? key}) : super(key: key);

  @override
  _PurchaseSupplierEvaluationListState createState() =>
      _PurchaseSupplierEvaluationListState();
}

class _PurchaseSupplierEvaluationListState
    extends State<PurchaseSupplierEvaluationList> {
  final GlobalKey<CryDataTableState> tableKey = GlobalKey<CryDataTableState>();
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> scaffoldStateKey = GlobalKey<ScaffoldState>();
  PageModel page =
      PageModel(orders: [OrderItemModel(column: 'create_date', asc: false)]);
  PurchaseSupplierEvaluation purchaseSupplierEvaluation =
      PurchaseSupplierEvaluation();
  List<PurchaseSupplierEvaluation> selectedList = [];
  List<SelectOptionVO> templateList = [];

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance!.addPostFrameCallback((c) {
      _query();
      _loadSelectVO();
    });
  }

  _loadSelectVO() async {
    templateList = await DynamicDataApi.getModelSelect(
      model: "purchase.evaluation.template",
      name: "template_name",
      active: false,
    );
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    var form = Form(
      key: formKey,
      child: Wrap(
        children: <Widget>[
          CrySelect(
            width: 280,
            label: '考评模板',
            dataList: templateList,
            value: purchaseSupplierEvaluation.templateId,
            onSaved: (v) {
              purchaseSupplierEvaluation.templateId = v;
            },
          ),
          CryInput(
            width: 180,
            label: '供应商编码',
            value: purchaseSupplierEvaluation.partnerCode,
            onSaved: (v) => {purchaseSupplierEvaluation.partnerCode = v},
          ),
          CryInput(
            width: 180,
            label: '供应商名称',
            value: purchaseSupplierEvaluation.partnerName,
            onSaved: (v) => {purchaseSupplierEvaluation.partnerName = v},
          ),
          YearsDate(
            context,
            width: 180,
            label: '考评开始月份',
            value: purchaseSupplierEvaluation.evaluationMonth,
            onSaved: (v) {
              purchaseSupplierEvaluation.evaluationMonth = v;
            },
          ),
          YearsDate(
            context,
            width: 180,
            label: '考评结束月份',
            value: purchaseSupplierEvaluation.writeDate,
            onSaved: (v) {
              purchaseSupplierEvaluation.writeDate = v;
            },
          ),
        ],
      ),
    );

    CryDataTable table = CryDataTable(
      key: tableKey,
      title: "数据列表",
      actions: !isDisplayDesktop(context)
          ? [
              _operationList(),
            ]
          : [],
      onPageChanged: (firstRowIndex) {
        page.current = (firstRowIndex ~/ page.size + 1);
        _loadData();
      },
      onRowsPerPageChanged: (int size) {
        page.size = size;
        page.current = 1;
        _loadData();
      },
      onSelectChanged: (Map selected) {
        this.setState(() {});
      },
      columns: [
        DataColumn(label: Text('考评月份')),
        DataColumn(label: Text('模板名称')),
        DataColumn(label: Text('供应商编码')),
        DataColumn(label: Text('供应商名称')),
        DataColumn(label: Text('考评得分')),
        DataColumn(label: Text('关键内容')),
        DataColumn(label: Text('关键事件')),
        DataColumn(label: Text('解决成效')),
        DataColumn(label: Text('交期评价')),
        DataColumn(label: Text('响应评价')),
        DataColumn(label: Text('质量评价')),
        DataColumn(label: Text('备注')),
      ],
      getCells: (m) {
        PurchaseSupplierEvaluation purchaseSupplierEvaluation =
            PurchaseSupplierEvaluation.fromMap(m);
        return [
          DataCell(Text(purchaseSupplierEvaluation.evaluationMonth ?? '--')),
          DataCell(Text(purchaseSupplierEvaluation.templateName ?? '--')),
          DataCell(Text(purchaseSupplierEvaluation.partnerCode ?? '--')),
          DataCell(Text(purchaseSupplierEvaluation.partnerName ?? '--')),
          DataCell(Text(purchaseSupplierEvaluation.score ?? '--')),
          DataCell(Text(purchaseSupplierEvaluation.GJNR != null
              ? purchaseSupplierEvaluation.GJNR.toString()
              : '--')),
          DataCell(Text(purchaseSupplierEvaluation.GJSJ != null
              ? purchaseSupplierEvaluation.GJSJ.toString()
              : '--')),
          DataCell(Text(purchaseSupplierEvaluation.JJCX != null
              ? purchaseSupplierEvaluation.JJCX.toString()
              : '--')),
          DataCell(Text(purchaseSupplierEvaluation.JQPJ != null
              ? purchaseSupplierEvaluation.JQPJ.toString()
              : '--')),
          DataCell(Text(purchaseSupplierEvaluation.XYFW != null
              ? purchaseSupplierEvaluation.XYFW.toString()
              : '--')),
          DataCell(Text(purchaseSupplierEvaluation.ZLPJ != null
              ? purchaseSupplierEvaluation.ZLPJ.toString()
              : '--')),
          DataCell(Text(purchaseSupplierEvaluation.comment ?? '--')),
        ];
      },
    );
    _getSelectList();
    CryButtonBar buttonBar = CryButtonBar(
      children: <Widget>[
        CryButtons.query(context, () => _query()),
        CryButtons.reset(context, () => _reset()),
        CryButtons.add(context, () => _edit(null)),
        CryButtons.edit(context,
            selectedList.length != 1 ? null : () => _edit(selectedList[0])),
        CryButtons.delete(context,
            selectedList.length < 1 ? null : () => _delete(selectedList)),
        CryButton(
            label: '评价',
            iconData: Icons.message,
            onPressed: selectedList.length != 1
                ? null
                : () => _evaluate(selectedList[0], false)),
        CryButton(
            label: '查看评价',
            onPressed: selectedList.length != 1
                ? null
                : () => _evaluate(selectedList[0], true)),
      ],
    );
    var result = Scaffold(
      key: scaffoldStateKey,
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          SizedBox(height: 10),
          isDisplayDesktop(context) ? form : Container(),
          isDisplayDesktop(context) ? buttonBar : Container(),
          Expanded(child: SingleChildScrollView(child: table)),
        ],
      ),
    );
    return result;
  }

  _edit(PurchaseSupplierEvaluation? purchaseSupplierEvaluation) async {
    showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: PurchaseSupplierEvaluationEdit(
          purchaseSupplierEvaluation: purchaseSupplierEvaluation,
        ),
      ),
    ).then((v) {
      if (v != null) {
        if (purchaseSupplierEvaluation == null) {
          // 新增时回到第一页
          tableKey.currentState?.pageTo(0);
        }
        _loadData();
      }
    });
  }

  _reset() {
    purchaseSupplierEvaluation = PurchaseSupplierEvaluation();
    formKey.currentState!.reset();
    _loadData();
  }

  _query() {
    formKey.currentState?.save();
    tableKey.currentState?.pageTo(0);
    _loadData();
  }

  _loadData() async {
    if ((purchaseSupplierEvaluation.evaluationMonth != "" &&
            purchaseSupplierEvaluation.evaluationMonth != null) &&
        (purchaseSupplierEvaluation.writeDate != "" &&
            purchaseSupplierEvaluation.writeDate != null)) {
      List<String> v1 = purchaseSupplierEvaluation.evaluationMonth!.split("-");
      List<String> v2 = purchaseSupplierEvaluation.writeDate!.split("-");
      if (int.parse(v1[0] + v1[1]) > int.parse(v2[0] + v2[1])) {
        CryUtils.message("开始月份应大于结束月份!");
        return;
      }
    }

    ResponseBodyApi responseBodyApi =
        await PurchaseSupplierEvaluationOdooApi.page(data: {
      "page": page,
      "domainList": purchaseSupplierEvaluation.toDomainList()
    });
    if (responseBodyApi.success!) {
      page = responseBodyApi.data != null ? responseBodyApi.data : PageModel();

      // WidgetsBinding.instance!.addPostFrameCallback((c) {
      tableKey.currentState!.loadData(page);
      // });
      _getSelectList();
    }
  }

  _delete(List<PurchaseSupplierEvaluation> selectedList) async {
    cryConfirm(context, S.of(context).confirmDelete, (context) async {
      List ids = selectedList.map((v) {
        return int.parse(v.id!);
      }).toList();
      var result = await PurchaseSupplierEvaluationOdooApi.removeByIds(ids);
      if (result.success!) {
        CryUtils.message(result.data["message"]);
        _query();
      }
    });
  }

  // _sort(column, {ascending}) {
  //   page.orders[0].column = column;
  //   page.orders[0].asc = ascending ?? !page.orders[0].asc!;
  //   _query();
  // }

  _search() {
    return showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: PurchaseSupplierEvaluationDialog(),
      ),
    ).then((v) {
      if (v != null) {
        purchaseSupplierEvaluation = v;
        _query();
      }
    });
  }

  _evaluate(PurchaseSupplierEvaluation? purchaseSupplierEvaluation,
      bool isView) async {
    if (!isView) {
      UserInfo userInfo = StoreUtil.getCurrentUserInfo();
      ResponseBodyApi responseBodyApi = await DynamicDataApi.getModels(
          model: "purchase.evaluation.project",
          key: "template_id",
          val: int.parse(purchaseSupplierEvaluation!.templateId!),
          key2: "dept_id",
          val2: int.parse(userInfo.deptId!));
      if (responseBodyApi.success!) {
        if (responseBodyApi.data.length == 0) {
          CryUtils.message("${userInfo.deptName}部门下暂未拥有对应的考评项目。");
          return;
        }
        final subscription = EventBus.getSubscriber()
            .where((event) => event["type"] == "form:saved")
            .listen(null);
        subscription.onData((data) {
          subscription.cancel();
          _query();
        });
        Utils.fullscreenDialog(Evaluate(
          purchaseSupplierEvaluation: purchaseSupplierEvaluation,
          project: responseBodyApi.data[0],
        ));
      }
    } else {
      ResponseBodyApi responseBodyApi = await DynamicDataApi.getModels(
        model: "purchase.evaluation.project",
        key: "template_id",
        val: int.parse(purchaseSupplierEvaluation!.templateId!),
      );
      if (responseBodyApi.success!) {
        if (responseBodyApi.data.length == 0) {
          CryUtils.message("没有考评项目！");
          return;
        }
        Utils.fullscreenDialog(EvaluateView(
          purchaseSupplierEvaluation: purchaseSupplierEvaluation,
          list: responseBodyApi.data,
        ));
      }
    }
  }

  _getSelectList() {
    selectedList = tableKey.currentState
            ?.getSelectedList(page)
            .map<PurchaseSupplierEvaluation>(
                (e) => PurchaseSupplierEvaluation.fromMap(e))
            .toList() ??
        [];
    setState(() {});
  }

  _operationList() {
    return PopupMenuButton(
      onSelected: (dynamic v) {
        if (v == OperationType.query) {
          _search();
        } else if (v == OperationType.add) {
          _edit(null);
        } else if (v == OperationType.edit) {
          _edit(selectedList[0]);
        } else if (v == OperationType.delete) {
          _delete(selectedList);
        } else if (v == OperationType.print) {
          _evaluate(selectedList[0], false);
        } else if (v == OperationType.handle) {
          _evaluate(selectedList[0], true);
        }
      },
      itemBuilder: (context) => <PopupMenuEntry<OperationType>>[
        PopupMenuItem<OperationType>(
          value: OperationType.query,
          child: ListTile(
            leading: const Icon(Icons.search),
            title: Text('查询'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.add,
          child: ListTile(
            leading: const Icon(Icons.add),
            title: Text('添加'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.edit,
          enabled: selectedList.length == 1,
          child: ListTile(
            leading: const Icon(Icons.edit),
            enabled: selectedList.length == 1,
            title: Text('修改'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.delete,
          enabled: selectedList.length != 0,
          child: ListTile(
            leading: const Icon(Icons.delete), //Icons.delete
            enabled: selectedList.length != 0,
            title: Text('删除'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.print,
          enabled: selectedList.length != 0,
          child: ListTile(
            //   leading: const Icon(Icons.delete), //Icons.delete
            enabled: selectedList.length != 0,
            title: Text('评价'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.handle,
          enabled: selectedList.length != 0,
          child: ListTile(
            // leading: const Icon(Icons.delete), //Icons.delete
            enabled: selectedList.length != 0,
            title: Text('查看评价'),
          ),
        ),
      ],
    );
  }
}
